import Vue from 'vue'
import Vuex from 'vuex'
import { SOME_MUTATION } from '@/store/mutation-type'
import foo from './modules/foo'
import bar from './modules/bar'
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    foo,
    bar
  },
  state: {
    count: 0,
    message: 'hello world',
    todos: [
      { id: 1, text: '吃饭', done: true },
      { id: 2, text: '睡觉', done: true },
      { id: 3, text: '打豆豆', done: false },
      { id: 4, text: '写代码', done: false }
    ]
  },
  /* 必须是同步函数 */
  mutations: {
    increment (state, { amount = 10 }) {
      state.count += amount
    },
    [SOME_MUTATION] (state) {
      state.message = 'hello world123123'
    },
    decrease(state) {
      state.count-- 
    }
  },
  /* 用于返回store中的专题太 */
  getters: {
    remaning: state => {
      return state.todos.filter(i => i.done === false).length
    },
    getTodoById: state => {
      return id => {
        return state.todos.find(i => i.id === id)
      }
    }
  },
  /* 类似 mutations 操作却是异步的
    Action 提交的是 mutation，而不是直接变更状态。
    Action 可以包含任意异步操作
    context.commit 调用mutations中的方法 来更改状态
    可以通过context.state或context.getters 获取state和getters
   */
  actions: {
    decrease(context) {
      context.commit('decrease')
    },
    async decreaseAsync({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('decrease')
          resolve()
        }, 1000)
      })
    },
    /**
     * dispatch 类似 this.$store.dispatch('')
     * 
     * @param {*} param0 
     */
    async decreaseAsyncB({ dispatch, commit }) {
      // 再次调用这个方法
      await dispatch('decreaseAsync')
      commit('decrease')
    },
    addIncrement({ commit }, { amount = 1 }){
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     commit({
      //       type: 'increment',
      //       amount
      //     })
      //     resolve()
      //   }, 1000)
      // })
      setTimeout(() =>{
        commit({
          type: 'increment',
          amount
        })
      }, 1000)
    }
  }
})
export default store